<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <link rel="icon" href="">
    <link rel="stylesheet" href="//unpkg.com/element-plus/dist/index.css"/>
    <script src="//unpkg.com/vue@next"></script>
    <script src="//unpkg.com/element-plus"></script>
    <title>Index</title>
</head>
<body>
<div id="app">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" status-icon>
        <el-form-item label="Username" prop="username">
            <el-input v-model="loginForm.username" name="username" type="text" autocomplete="on"></el-input>
        </el-form-item>
        <el-form-item label="Password" prop="password">
            <el-input v-model="loginForm.password" name="password" type="password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submitForm('loginForm')">Submit</el-button>
            <el-button @click="resetForm('loginForm')">Reset</el-button>
        </el-form-item>
    </el-form>
</div>
<script>
    const app = Vue.createApp({
        data() {
            const validateInput = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('Please input'))
                } else {
                    callback()
                }
            }
            return {
                loginForm: {
                    username: 'zhangsan',
                    password: 'password'
                },
                loginRules: {
                    username: [{validator: validateInput, trigger: 'blur'}],
                    password: [{validator: validateInput, trigger: 'blur'}]
                }
            }
        },
        methods: {
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        // https://www.ruanyifeng.com/blog/2020/12/fetch-tutorial.html
                        fetch("/login", {
                            method: "POST",
                            body: new FormData(this.$refs['loginForm'].$el)
                        }).then(response => {
                            return response.json();
                        }).then(json => {
                            console.info(json);
                            localStorage.setItem("tokenHead", json.data.tokenHead);
                            localStorage.setItem("tokenValue", json.data.tokenValue);
                            // window.location.href = "router.html";
                        }).catch(error => {
                            console.error(error);
                        })
                    }
                })
            },
            resetForm(formName) {
                this.$refs[formName].resetFields();
            }
        }
    });
    app.use(ElementPlus);
    app.mount("#app");
</script>
</body>
</html>